package com.wei.czz.framework.admin.manager;

import com.wei.czz.common.dto.admin.UserDto;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.enums.rabbitMQ.MqEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.utils.CopyUtils;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.vo.admin.user.BindUserVo;
import com.wei.czz.common.vo.admin.userRoleGroup.UserRoleGroupFormVo;
import com.wei.czz.framework.admin.entity.DeptUserEntity;
import com.wei.czz.framework.admin.entity.UserEntity;
import com.wei.czz.framework.admin.entity.UserRoleGroupEntity;
import com.wei.czz.framework.admin.service.DeptService;
import com.wei.czz.framework.admin.service.DeptUserService;
import com.wei.czz.framework.admin.service.UserRoleGroupService;
import com.wei.czz.framework.admin.service.UserService;
import com.wei.czz.framework.common.helper.RabbitHelper;
import com.wei.czz.framework.rabbitMQ.message.roleSpace.RoleSpaceUserUpdateMessage;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2024-10-30 21:12:42
 * className: UserRoleGroupManager
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class UserRoleGroupManager {

    private static final Logger log = LoggerFactory.getLogger(UserRoleGroupManager.class);

    private final UserRoleGroupService userRoleGroupService;

    private final UserService userService;

    private final DeptService deptService;

    private final DeptUserService deptUserService;

    private final RabbitHelper rabbitHelper;

    public void bindUser(BindUserVo bindUserVo) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        /*
            获取角色授权组已关联用户列表
         */
        List<UserRoleGroupEntity> userRoleGroupList = userRoleGroupService.findList(
                Collections.singletonList(bindUserVo.getMasterId()), null, null
        );
        Map<Long, UserRoleGroupEntity> userRoleGroupMap = new HashMap<>();
        List<UserRoleGroupEntity> deletedList = new ArrayList<>();
        for (UserRoleGroupEntity userRoleGroup : userRoleGroupList) {
            if (CommonEnum.ZERO.getValue().equals(userRoleGroup.getDeleteStatus())) {
                userRoleGroupMap.put(userRoleGroup.getUserId(), userRoleGroup);
            } else {
                deletedList.add(userRoleGroup);
            }
        }
        log.info("已关联数量：{}", userRoleGroupMap.size());
        log.info("已删除数量：{}", deletedList.size());
        Iterator<UserRoleGroupEntity> deletedIterator = deletedList.iterator();

        List<UserRoleGroupEntity> saveList = new ArrayList<>();
        List<UserRoleGroupEntity> updateList = new ArrayList<>();

        for (Long userId : bindUserVo.getUserIdList()) {
            UserRoleGroupEntity userRoleGroup = userRoleGroupMap.remove(userId);
            if (Objects.nonNull(userRoleGroup)) {
                // 已关联，过滤
                continue;
            }
            // 新关联，添加数据
            if (deletedIterator.hasNext()) {
                userRoleGroup = deletedIterator.next();

                UserRoleGroupEntity updateUserRoleGroup = new UserRoleGroupEntity();
                updateUserRoleGroup.setId(userRoleGroup.getId())
                        .setUserId(userId)
                        .setDeleteStatus(CommonEnum.ZERO.getValue())
                        .setUpdateTime(date)
                        .setUpdateUser(userPo.getUsername())
                        .setUpdateUserId(userPo.getUserId());
                updateList.add(updateUserRoleGroup);
            }
            if (Objects.isNull(userRoleGroup)) {
                userRoleGroup = new UserRoleGroupEntity();
                userRoleGroup.setSpaceId(bindUserVo.getMasterId())
                        .setUserId(userId)
                        .setDeleteStatus(CommonEnum.ZERO.getValue())
                        .setUpdateTime(date)
                        .setUpdateUser(StringUtils.EMPTY)
                        .setUpdateUserId(CommonEnum.ZERO.getLongValue())
                        .setCreateTime(date)
                        .setCreateUser(userPo.getUsername())
                        .setCreateUserId(userPo.getUserId());
                saveList.add(userRoleGroup);
            }
        }
        if (saveList.isEmpty() && updateList.isEmpty()) {
            log.info("角色授权组没有新关联的用户");
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "您选择的用户已关联，请确认后重新操作");
        }

        /*
            保存
         */
        if (!saveList.isEmpty()) {
            userRoleGroupService.batchSave(saveList);
        }

        /*
            修改
         */
        if (!updateList.isEmpty()) {
            userRoleGroupService.batchUpdate(updateList);
        }

        if (!saveList.isEmpty() || !updateList.isEmpty()) {
            RoleSpaceUserUpdateMessage roleSpaceUserUpdateMessage = CopyUtils.map(bindUserVo, RoleSpaceUserUpdateMessage.class);
            roleSpaceUserUpdateMessage.setOptType(CommonEnum.ZERO.getValue());
            // 发送MQ消息
            rabbitHelper.send(MqEnum.ROLE_SPACE_USER, roleSpaceUserUpdateMessage);
        }
    }

    public PageDto<UserDto> getPageList(UserRoleGroupFormVo formVo) {

        /*
            分页获取用户
         */
        PageDto<UserEntity> pageDto = userService.getUserRoleGroupPageList(formVo);
        if (pageDto.isEmpty()) {
            return pageDto.rebuild();
        }
        List<UserEntity> userList = pageDto.getList();
        // 收集用户主键
        List<Long> userIdList = CopyUtils.mapList(userList, UserEntity::getUserId);

        /*
            获取用户关联部门
         */
        List<DeptUserEntity> deptUserList = deptUserService.findList(null, userIdList);
        // 收集部门主键
        List<Long> deptIdList = new ArrayList<>();
        Map<Long, List<Long>> deptUserMap = new HashMap<>();
        for (DeptUserEntity deptUser : deptUserList) {
            deptIdList.add(deptUser.getDeptId());
            List<Long> _deptIdList = deptUserMap.computeIfAbsent(deptUser.getUserId(), k -> new ArrayList<>());
            _deptIdList.add(deptUser.getDeptId());
        }
        log.info("deptIdList={}", deptIdList);
        log.info("deptUserMap={}", deptUserMap);

        /*
            获取部门名称映射
         */
        Map<Long, String> deptNameMap = deptService.getDeptNameMap(deptIdList, Function.identity());
        log.info("deptNameMap={}", deptNameMap);

        StringBuilder sb = new StringBuilder();

        List<UserDto> list = new ArrayList<>();
        for (UserEntity user : userList) {
            sb.delete(0, sb.length());

            deptIdList = deptUserMap.getOrDefault(user.getUserId(), Collections.emptyList());
            for (Long deptId : deptIdList) {
                String deptName = deptNameMap.get(deptId);
                if (StringUtils.isNotBlank(deptName)) {
                    sb.append(deptName).append("、");
                }
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }

            UserDto userDto = new UserDto();
            userDto.setUserId(user.getUserId().toString())
                    .setDeptNames(sb.toString())
                    .setUsername(user.getUsername())
                    .setStatus(user.getStatus())
                    .setStatusName(CommonEnum.getStatusName(user.getStatus()));

            list.add(userDto);
        }

        // 封装返回
        return pageDto.rebuild(list);
    }

    public void unbindUser(BindUserVo bindUserVo) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        /*
            获取角色授权组已关联用户列表
         */
        List<UserRoleGroupEntity> userRoleGroupList = userRoleGroupService.findList(
                Collections.singletonList(bindUserVo.getMasterId()), bindUserVo.getUserIdList(),
                CommonEnum.ZERO.getValue()
        );
        if (userRoleGroupList.isEmpty()) {
            log.info("获取角色授权组已关联用户结果为空");
            throw new CzzException(ResultEnum.REFRESH.getCode(), "选中用户已解除绑定，请确认后重新操作");
        }

        Function<UserRoleGroupEntity, UserRoleGroupEntity> function = roleGroup -> {
            UserRoleGroupEntity updateUserRoleGroup = new UserRoleGroupEntity();
            updateUserRoleGroup.setId(roleGroup.getId())
                    .setDeleteStatus(CommonEnum.ONE.getValue())
                    .setUpdateTime(date)
                    .setUpdateUser(userPo.getUsername())
                    .setUpdateUserId(userPo.getUserId());
            return updateUserRoleGroup;
        };
        List<UserRoleGroupEntity> updateList = CopyUtils.mapList(userRoleGroupList, function);

        /*
            修改
         */
        userRoleGroupService.batchUpdate(updateList);

        RoleSpaceUserUpdateMessage roleSpaceUserUpdateMessage = CopyUtils.map(bindUserVo, RoleSpaceUserUpdateMessage.class);
        roleSpaceUserUpdateMessage.setOptType(CommonEnum.ONE.getValue());
        // 发送MQ消息
        rabbitHelper.send(MqEnum.ROLE_SPACE_USER, roleSpaceUserUpdateMessage);
    }
}
